package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.MessageUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.widget.CheckLineView;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

public class AddDelegateTaskFragment extends Fragment implements OnClickListener {

  /** 要求完成时间 */
  private static final int REQUEST_ACQUIRE_FINISHTIME = 0;

  /** 执行人 */
  private static final int REQUEST_CHOOSE_TRANSACTOR = 3;
  /** 委派任务列表 */
  //private static final int LIST_DELEGATETASK = 1;
  /**
   * 计划类别
   */
  private static final int REQUEST_PLAN_KIND = 2;

  protected static final String TAG = "AddDelegateTaskFragment";
  @BindView(R.id.clv_instationNotify) CheckLineView clvInstationNotify;
  @BindView(R.id.clv_SMSNotify) CheckLineView clvSMSNotify;

  private BaseVolleyActivity mActivity;
  private TextView et_putAppointer_workProcess; // 委派人
  private TextView et_putTransactor_workProcess; // 执行人
  private TextView et_putRequestTime_workProcess; // 要求完成时间
  private TextView et_putPlanClass_workProcess; // 计划类别
  private EditText et_putPlanContent_workProcess; // 计划内容

  /** 委派人 */
  //private String mApointer;
  /** 委派人JobNo */
  //private String mApointerJobNo;

  /** 工作类别名称 */
  private String mPlanKindName;
  /** 工作类别编码 */
  private String mPlanKindCode;
  /** 要求完成时间 */
  private String mAcquireTime;
  /** 本阶段完成时间 */
  //private String mStageTime;
  private String mExcManName; // 执行人姓名
  private String mExcManId; // 执行人工号
  private CurrentUser mCurrentUser;// 当前登录人信息

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);

    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();

    if (actionBar != null) {
      actionBar.setTitle(R.string.adddelegateTask);

      if (NavUtils.getParentActivityName(getActivity()) != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
      }
    }

    mCurrentUser = CurrentUser.newInstance(getActivity());
    super.onCreate(savedInstanceState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //MenuInflater menuInflater = new MenuInflater(getActivity());
    inflater.inflate(R.menu.menu_confirm, menu);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_adddelegate_task, container, false);
    ButterKnife.bind(this, view);
    initView(view);
    return view;
  }

  private void initView(View view) {
    et_putAppointer_workProcess = (TextView) view.findViewById(R.id.et_putAppointer_workProcess);
    et_putAppointer_workProcess.setText(mCurrentUser.getRealName());
    et_putTransactor_workProcess = (TextView) view.findViewById(R.id.et_putTransactor_workProcess);
    et_putRequestTime_workProcess =
        (TextView) view.findViewById(R.id.et_putRequestTime_workProcess);
    et_putPlanClass_workProcess = (TextView) view.findViewById(R.id.et_putPlanClass_workProcess);
    et_putPlanContent_workProcess =
        (EditText) view.findViewById(R.id.et_putPlanContent_workProcess);
    et_putAppointer_workProcess.setOnClickListener(this);
    et_putTransactor_workProcess.setOnClickListener(this);
    et_putPlanClass_workProcess.setOnClickListener(this);
    et_putRequestTime_workProcess.setOnClickListener(this);

    mAcquireTime = DateUtil.dateToString(new Date(), DateUtil.TYPE_DATE);

    et_putRequestTime_workProcess.setText(mAcquireTime);
  }

  // 判断要填写的是否填写完整及对于书写的验证
  private void saveWorkProcessEdit() {
    boolean isEmpty = MyUtils.isEmptyText(et_putAppointer_workProcess)
        || MyUtils.isEmptyText(et_putTransactor_workProcess)
        || MyUtils.isEmptyText(et_putRequestTime_workProcess)
        || MyUtils.isEmptyText(et_putPlanClass_workProcess)
        || MyUtils.isEmptyText(et_putPlanContent_workProcess);

    if (isEmpty) {
      Toast.makeText(getActivity(), R.string.notComplete, Toast.LENGTH_SHORT).show();
      return;
    }

    // 提交提示对话框
    AlertDialog.Builder dialog = new AlertDialog.Builder(mActivity);
    dialog.setTitle(R.string.restart_title);
    dialog.setMessage(R.string.cannotEdit);

    dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        volleyPostSave();
      }
    });

    dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
      }
    });
    dialog.create().show();
  }

  private void volleyPostSave() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TEMPORARY_PLAN);
    HashMap<String, String> mTemporaryPlan = new HashMap<>();

    String planContentDesc = et_putPlanContent_workProcess.getText().toString();

    String id = UUID.randomUUID().toString();

    mTemporaryPlan.put("id", id);
    mTemporaryPlan.put("taskManName", mCurrentUser.getRealName());
    mTemporaryPlan.put("taskManId", mCurrentUser.getJobNumber());
    mTemporaryPlan.put("planEsteTime", mAcquireTime);
    mTemporaryPlan.put("planKindName", mPlanKindName);
    mTemporaryPlan.put("planKindCode", mPlanKindCode);
    mTemporaryPlan.put("planContentDesc", planContentDesc);
    mTemporaryPlan.put("excManName", mExcManName);
    mTemporaryPlan.put("excManId", mExcManId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, mTemporaryPlan, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
          if (clvInstationNotify.getCbCheck().isChecked()) {
            String content = getString(R.string.newWorkMessage, getString(R.string.appoint));
            MessageUtil.sendReport(mActivity, mExcManId, mExcManName, content);
          }
          if (clvSMSNotify.getCbCheck().isChecked()) {
            String content = getString(R.string.newWorkMessage, getString(R.string.appoint));
            MessageUtil.sendSMS(mActivity, mExcManId, content);
          }

          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_confirm:
        saveWorkProcessEdit();
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onClick(View arg0) {
    switch (arg0.getId()) {
      case R.id.et_putTransactor_workProcess:

        showDialog(REQUEST_CHOOSE_TRANSACTOR);

        break;
      case R.id.et_putPlanClass_workProcess:

        showDialog(REQUEST_PLAN_KIND);

        break;
      case R.id.et_putRequestTime_workProcess:

        showDialog(REQUEST_ACQUIRE_FINISHTIME);

        break;
    }
  }

  /**
   * 显示时间对话框
   *
   * @param requestCode 请求码
   */
  public void showDialog(int requestCode) {
    DialogFragment dialog = null;

    switch (requestCode) {
      case REQUEST_ACQUIRE_FINISHTIME:
        dialog = new BaseYMDTimeDialogFragment();
        break;

      case REQUEST_CHOOSE_TRANSACTOR:
        Intent i = new Intent(getActivity(), AppointerListActivity.class);
        startActivityForResult(i, requestCode);
        return;

      case REQUEST_PLAN_KIND:
        Intent intent = new Intent(getActivity(), PlanKindListActivity.class);
        startActivityForResult(intent, requestCode);
        return;
      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    if (dialog != null) {
      dialog.setTargetFragment(AddDelegateTaskFragment.this, requestCode);
      dialog.show(fm, "");
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_ACQUIRE_FINISHTIME && data != null) {
      Date acquireDate = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      //			mAcquireTime = MyDateUtil.dateToString(acquireDate);
      mAcquireTime = DateUtil.dateToString(acquireDate, DateUtil.TYPE_DATE);

      et_putRequestTime_workProcess.setText(mAcquireTime);

      return;
    }

    if (requestCode == REQUEST_CHOOSE_TRANSACTOR && data != null) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);

      mExcManName = customer.getName();// 执行人姓名
      mExcManId = customer.getId();// 执行人工号
      et_putTransactor_workProcess.setText(mExcManName);

      return;
    }

    if (requestCode == REQUEST_PLAN_KIND && data != null) {
      CustomerDialog planKind =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      mPlanKindName = planKind.getName();
      mPlanKindCode = planKind.getId();
      et_putPlanClass_workProcess.setText(mPlanKindName);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}